# -*- coding: utf-8 -*-

from sqlalchemy.orm import relationship
from sqlalchemy import Column, String, Integer, BigInteger, Date, DateTime, ForeignKey, func
from .database import Base


# 模型类
class City(Base):
    __tablename__ = "city"
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    country_code = Column(String(100), nullable=False, comment="国家编码")
    country = Column(String(100), nullable=False, comment="国家名称")
    country_population = Column(BigInteger, nullable=False, comment="国家人口")
    province = Column(String(100), unique=True, nullable=False, comment="省/直辖市")
    # Data是关联的类名，back_population是反向访问的属性名
    data = relationship('Data', back_populates='city')
    create_date = Column(DateTime, server_default=func.now(), comment="创建时间")
    update_date = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment="更新时间")
    # __mapper_args__ = {"order_by": country_code.desc()}

    def __repr__(self):
        return f'{self.country}_{self.province}'


class Data(Base):
    __tablename__ = "data"
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    city_id = Column(String, ForeignKey('city.id'), comment='所属省/直辖市')
    date = Column(Date, nullable=False, comment="数据生成日期")
    confirmed = Column(BigInteger, default=0, nullable=False, comment="确诊数量")
    death = Column(BigInteger, default=0, nullable=False, comment="死亡数量")
    recovered = Column(BigInteger, default=0, nullable=False, comment="治愈数量")
    city = relationship('City', back_populates="data")
    create_date = Column(DateTime, server_default=func.now(), comment="创建时间")
    update_date = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment="更新时间")
    # __mapper_args__ = {"order_by": date.desc()}

    def __repr__(self):
        return f'{repr(self.date)}:确诊{self.confirmed}例'


""" SQLAlchemy教程

SQLAlchemy的基本操作大全
    http://www.taodudu.cc/news/show-175725.html
Python3+SQLAlchemy+Sqlite3实现ORM教程
    https://www.cnblogs.com/jiangxiaobo/p/12350561.html
SQLAlchemy基础知识Autoflush和Autocommit
    https://zhuanlan.zhihu.com/p/48994990

"""



